//
//  AppDelegate.m
//  ShangAPP
//
//  Created by macpro on 16/1/21.
//  Copyright © 2016年 wangdao. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import <MAMapKit/MAMapKit.h>
#import "MyTools.h"
#import "JPUSHService.h"
#import "HTTPServer.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    [MAMapServices sharedServices].apiKey = @"3c1ed8e77fcfcd1f388026c38564fe01";

    
    self.window.backgroundColor = [UIColor whiteColor];
    ViewController *vc = [[ViewController alloc]init];
    UINavigationController *nc = [[UINavigationController alloc]initWithRootViewController:vc];
    _window.rootViewController = nc;
    
    [self.window makeKeyAndVisible];
    
    
    

    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |UIUserNotificationTypeSound | UIUserNotificationTypeAlert)     categories:nil];
    } else {
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)
         
                                              categories:nil];
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)
         //注册通知类型
                                              categories:nil];
    }
    //启动SDK
    [JPUSHService setupWithOption:launchOptions appKey:@"f368e33d72627318d57c85b5" channel:nil apsForProduction:NO];
    

    
    
    return YES;
}

#pragma mark 极光
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"DeviceToken 获取失败，原因：%@",error);
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required处理收到的 APNs 消息
    [JPUSHService handleRemoteNotification:userInfo];
}

//判断角标个数,若不为0则创建通知
- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    if ((long)[UIApplication sharedApplication].applicationIconBadgeNumber == 0) {
        
    }else{
        
        NSNotification *mynotification = [NSNotification notificationWithName:@"icon" object:self userInfo:nil];
        [[NSNotificationCenter defaultCenter] postNotification:mynotification];
    }
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];   //清除角标
    [JPUSHService setBadge:0];
    [JPUSHService resetBadge];
    
    [self startServer];
    //创建通知
    NSNotification *notification =[NSNotification notificationWithName:@"paoma" object:nil userInfo:nil];
    //通过通知中心发送通知
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    //
    //    if (userInfo) {
    //        completionHandler(UIBackgroundFetchResultNewData);
    //
    //        UILocalNotification *notification = [JPUSHService setLocalNotification:[NSDate dateWithTimeIntervalSinceNow:1]
    //                                                                     alertBody:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]
    //                                                                         badge:0
    //                                                                   alertAction:nil
    //                                                                 identifierKey:@"Jpush1"
    //                                                                      userInfo:userInfo
    //                                                                     soundName:UILocalNotificationDefaultSoundName];
    //
    //        //添加推送到UIApplication
    //        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    //
    //        // IOS 7 Support Required
    //        [JPUSHService handleRemoteNotification:userInfo];
    //
    //
    //    } else {
    //        completionHandler(UIBackgroundFetchResultNoData);
    //    }
}

#pragma mark .前台后台运行
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    
    NSNotification *mynotification = [NSNotification notificationWithName:@"Jpush" object:self userInfo:notification.userInfo];
    [[NSNotificationCenter defaultCenter] postNotification:mynotification];
    
    if (application.applicationState == UIApplicationStateBackground) {
        NSLog(@"不知道干嘛的。。。。");
        
        NSNotification *mynotification = [NSNotification notificationWithName:@"Background" object:self userInfo:notification.userInfo];
        [[NSNotificationCenter defaultCenter] postNotification:mynotification];
        
    }else if (application.applicationState == UIApplicationStateInactive  || application.applicationState == UIApplicationStateActive){
        NSLog(@"后台或者前台运行~");
        
        NSNotification *mynotification = [NSNotification notificationWithName:@"Active" object:self userInfo:notification.userInfo];
        [[NSNotificationCenter defaultCenter] postNotification:mynotification];
    }
}

- (void)startServer
{
    // Start the server (and check for problems)
    
    NSError *error;
    if([httpServer start:&error])
    {
        NSLog(@"Started HTTP Server on port %hu", [httpServer listeningPort]);
    }
    else
    {
        NSLog(@"Error starting HTTP Server: %@", error);
    }
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}



- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
